﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace BPMS.Utility.Web
{
    public class FormsAuthenticationService
    {
        private readonly HttpContext httpContext;

        public FormsAuthenticationService()
        {
            httpContext = HttpContext.Current;
        }

        public FormsAuthenticationService(HttpContext httpContext)
        {
            this.httpContext = httpContext;
        }

        public void SignIn(string username, bool useCookie)
        {
            var timeNow = DateTime.UtcNow.ToLocalTime();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                username,
                timeNow,
                timeNow.Add(FormsAuthentication.Timeout),
                useCookie,
                username,
                FormsAuthentication.FormsCookiePath);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }
            httpContext.Response.Cookies.Add(cookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
            httpContext.Response.Cookies.Clear();
            HttpContext.Current.Session.Clear();
        }

        public string GetAuthenticatedNameByTicket()
        {
            if (httpContext == null ||
                httpContext.Request == null ||
                httpContext.Request.IsAuthenticated)
            {
                return string.Empty;
            }
            var formsIdentity = httpContext.User.Identity as FormsIdentity;
            if (null == formsIdentity)
                return string.Empty;
            return formsIdentity.Ticket.Name;
        }
    }
}
